<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 供应商结账管理
 *
 * @icon fa fa-money
 * @remark 管理供应商付款、应付账款、发票等财务业务
 */
class SupplierPayment extends Backend
{
    /**
     * SupplierPayment模型对象
     * @var \app\admin\model\scanwork\SupplierPayment
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\SupplierPayment;
        
        // 获取供应商列表
        $supplierList = \app\admin\model\scanwork\Supplier::where('status', 1)->column('name', 'id');
        $this->view->assign("supplierList", $supplierList);
    }

    /**
     * 应付账款列表
     */
    public function payable()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = Db::name('scanwork_supplier_payable')
                ->alias('sp')
                ->join('scanwork_supplier s', 'sp.supplier_id = s.id', 'left')
                ->join('scanwork_purchase_inbound pi', 'sp.purchase_inbound_id = pi.id', 'left')
                ->field('sp.*, s.name as supplier_name, pi.inbound_no')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $total = Db::name('scanwork_supplier_payable')
                ->alias('sp')
                ->join('scanwork_supplier s', 'sp.supplier_id = s.id', 'left')
                ->where($where)
                ->count();

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 付款记录列表
     */
    public function payment()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = Db::name('scanwork_supplier_payment')
                ->alias('sp')
                ->join('scanwork_supplier s', 'sp.supplier_id = s.id', 'left')
                ->join('scanwork_supplier_payable spa', 'sp.payable_id = spa.id', 'left')
                ->field('sp.*, s.name as supplier_name, spa.payable_no')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $total = Db::name('scanwork_supplier_payment')
                ->alias('sp')
                ->join('scanwork_supplier s', 'sp.supplier_id = s.id', 'left')
                ->where($where)
                ->count();

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 发票管理列表
     */
    public function invoice()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = Db::name('scanwork_supplier_invoice')
                ->alias('si')
                ->join('scanwork_supplier s', 'si.supplier_id = s.id', 'left')
                ->join('scanwork_purchase_inbound pi', 'si.purchase_inbound_id = pi.id', 'left')
                ->field('si.*, s.name as supplier_name, pi.inbound_no')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $total = Db::name('scanwork_supplier_invoice')
                ->alias('si')
                ->join('scanwork_supplier s', 'si.supplier_id = s.id', 'left')
                ->where($where)
                ->count();

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 创建应付账款
     */
    public function createPayable()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 生成应付账款编号
                $params['payable_no'] = 'PAY' . date('YmdHis') . rand(1000, 9999);
                
                // 计算剩余应付金额
                $params['remaining_amount'] = $params['total_amount'] - $params['paid_amount'];
                
                // 设置状态
                if ($params['paid_amount'] >= $params['total_amount']) {
                    $params['status'] = 'paid';
                } elseif ($params['paid_amount'] > 0) {
                    $params['status'] = 'partial';
                } else {
                    $params['status'] = 'pending';
                }
                
                $result = false;
                Db::startTrans();
                try {
                    $result = Db::name('scanwork_supplier_payable')->insert($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 创建付款记录
     */
    public function createPayment()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 生成付款单号
                $params['payment_no'] = 'PAY' . date('YmdHis') . rand(1000, 9999);
                
                // 设置操作员
                $params['operator_id'] = $this->auth->id;
                
                $result = false;
                Db::startTrans();
                try {
                    // 插入付款记录
                    $paymentId = Db::name('scanwork_supplier_payment')->insertGetId($params);
                    
                    // 更新应付账款
                    if ($params['payable_id']) {
                        $payable = Db::name('scanwork_supplier_payable')->find($params['payable_id']);
                        if ($payable) {
                            $newPaidAmount = $payable['paid_amount'] + $params['payment_amount'];
                            $newRemainingAmount = $payable['total_amount'] - $newPaidAmount;
                            
                            $updateData = [
                                'paid_amount' => $newPaidAmount,
                                'remaining_amount' => $newRemainingAmount
                            ];
                            
                            if ($newPaidAmount >= $payable['total_amount']) {
                                $updateData['status'] = 'paid';
                            } elseif ($newPaidAmount > 0) {
                                $updateData['status'] = 'partial';
                            }
                            
                            Db::name('scanwork_supplier_payable')->where('id', $params['payable_id'])->update($updateData);
                        }
                    }
                    
                    Db::commit();
                    $this->success('付款记录创建成功');
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 从采购入库单创建应付账款
     */
    public function createPayableFromInbound()
    {
        if ($this->request->isPost()) {
            $inboundIds = $this->request->post('inbound_ids');
            if (empty($inboundIds)) {
                $this->error('请选择要创建应付账款的入库单');
            }

            Db::startTrans();
            try {
                $inbounds = Db::name('scanwork_purchase_inbound')
                    ->alias('pi')
                    ->join('scanwork_supplier s', 'pi.supplier_id = s.id', 'left')
                    ->field('pi.*, s.name as supplier_name')
                    ->where('pi.id', 'in', $inboundIds)
                    ->where('pi.status', 2) // 已入库
                    ->select();

                if (empty($inbounds)) {
                    throw new Exception('没有找到已入库的采购入库单');
                }

                $payableIds = [];
                foreach ($inbounds as $inbound) {
                    // 检查是否已创建应付账款
                    $existingPayable = Db::name('scanwork_supplier_payable')
                        ->where('purchase_inbound_id', $inbound['id'])
                        ->find();
                    
                    if ($existingPayable) {
                        continue; // 跳过已创建应付账款的入库单
                    }

                    // 创建应付账款
                    $payableData = [
                        'payable_no' => 'PAY' . date('YmdHis') . rand(1000, 9999),
                        'supplier_id' => $inbound['supplier_id'],
                        'purchase_inbound_id' => $inbound['id'],
                        'total_amount' => $inbound['total_amount'],
                        'paid_amount' => 0.00,
                        'remaining_amount' => $inbound['total_amount'],
                        'due_date' => date('Y-m-d', strtotime('+30 days')), // 默认30天付款期
                        'status' => 'pending',
                        'createtime' => time(),
                        'updatetime' => time()
                    ];

                    $payableId = Db::name('scanwork_supplier_payable')->insertGetId($payableData);
                    $payableIds[] = $payableId;
                }

                Db::commit();
                $this->success('应付账款创建成功，共创建 ' . count($payableIds) . ' 条记录');
                
            } catch (Exception $e) {
                Db::rollback();
                $this->error('创建失败：' . $e->getMessage());
            }
        }

        // 获取已入库但未创建应付账款的入库单
        $inbounds = Db::name('scanwork_purchase_inbound')
            ->alias('pi')
            ->join('scanwork_supplier s', 'pi.supplier_id = s.id', 'left')
            ->join('scanwork_supplier_payable sp', 'pi.id = sp.purchase_inbound_id', 'left')
            ->field('pi.*, s.name as supplier_name')
            ->where('pi.status', 2) // 已入库
            ->where('sp.id', 'null') // 未创建应付账款
            ->select();

        $this->view->assign('inbounds', $inbounds);
        return $this->view->fetch();
    }

    /**
     * 供应商对账
     */
    public function reconciliation()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 生成对账编号
                $params['reconciliation_no'] = 'REC' . date('YmdHis') . rand(1000, 9999);
                
                // 计算差异金额
                $params['difference_amount'] = $params['our_amount'] - $params['supplier_amount'];
                
                // 设置操作员
                $params['operator_id'] = $this->auth->id;
                
                $result = false;
                Db::startTrans();
                try {
                    $result = Db::name('scanwork_supplier_reconciliation')->insert($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 获取供应商应付账款统计
     */
    public function getSupplierPayableStats()
    {
        if ($this->request->isAjax()) {
            $supplierId = $this->request->param('supplier_id');
            
            $where = [];
            if ($supplierId) {
                $where['supplier_id'] = $supplierId;
            }
            
            $stats = Db::name('scanwork_supplier_payable')
                ->where($where)
                ->field([
                    'COUNT(*) as total_count',
                    'SUM(total_amount) as total_amount',
                    'SUM(paid_amount) as paid_amount',
                    'SUM(remaining_amount) as remaining_amount',
                    'SUM(CASE WHEN status = "pending" THEN 1 ELSE 0 END) as pending_count',
                    'SUM(CASE WHEN status = "partial" THEN 1 ELSE 0 END) as partial_count',
                    'SUM(CASE WHEN status = "paid" THEN 1 ELSE 0 END) as paid_count',
                    'SUM(CASE WHEN status = "overdue" THEN 1 ELSE 0 END) as overdue_count'
                ])
                ->find();
            
            $this->success('获取成功', '', $stats);
        }
    }
}
